//
//  MainViewController.m
//  customerGuide
//
//  Created by 王鹏宇 on 2017/4/1.
//  Copyright © 2017年 王鹏宇. All rights reserved.
//

#import "MainViewController.h"
#import "PopHeaderView.h"
#import <Accelerate/Accelerate.h>
#import "MapVC.h"
#import "ScenicSpotViewController.h"
#import "SearchViewController.h"
#import "TitleView.h"
#import "GuiderVC.h"
#import "ScenicDescribeVC.h"
#import "FileManager.h"
#import "CityTourCardVC.h"
#import "CityTourIntroduceCell.h"
#import "MainRecommendVC.h"

#import "YYCForceUpdateVC.h"

#import "UIImage+BlurView.h"

#import "HomeQuestionAlertVC.h"

#import "JMHoledView.h"

#import "RaidersViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "TabItem.h"
#import "LoginVC.h"
#import "WebViewVC.h"
#import "LinePreDetailVC.h"


#import "AskQuestionVC.h"
#import "PhoneInfo.h"

#define cellHight   ([UIScreen mainScreen].bounds.size.width + 150)
#define effectValue 20
@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,PopHeaderViewDelegate,TitleViewDelegate,SearchViewControllerDelegate>

@property (nonatomic, strong) TitleView *titleView;
@property (nonatomic, strong) PopHeaderView *popHeaderView;

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImageView *obfuscationImageView;
//@property (nonatomic, strong) UIView *darkView;

@property (nonatomic, strong) UIView *tableViewHeaderView;

@property (nonatomic, strong) UIButton *backBtn;

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic) CGFloat currentOffset;

@property (nonatomic) BOOL hasLoad;

@property (nonatomic) BOOL needReGuide;
@property (nonatomic) BOOL needReAlertCity;

@end

@implementation MainViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.tableView.contentOffset.y == 0) {
        self.navigationItem.rightBarButtonItem = nil;
    }
    if (self.isAinamation) {
        [self initLocation];
    }
    
    [MobClick beginLogPageView:@"1"];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [MobClick endLogPageView:@"1"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.delegate = nil;
    
    if (!self.navigationItem.rightBarButtonItem) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
        self.backBtn.alpha = 0;
    }
    
    if (self.tableView.contentOffset.y == 0) {
        
        self.backBtn.alpha = 0;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.hasLoad = YES;
        
        [self updateApp];
        [self appMark];
        
        [self showQuestion];
        
        [self operationApp:nil];
        
    });
    
    if (self.needReGuide) {
        [self newGuidePage];
    } else if (self.needReAlertCity) {
        [self alertLocationCity];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
    
    NSString *chid = [UserManager sharedManager].chid;
    
    if (chid) {
        [daDict setObject:chid forKey:@"chid"];
    }
    
    NSDictionary *phoneDict = [PhoneInfo shareInfo].infoDict;
    
    if (phoneDict) {
        [daDict setValuesForKeysWithDictionary:phoneDict];
    }
    
    [NetAPIManager postPhoneData:daDict];
    
    [self setUpNavigationItem];
    [self setupBg];
    [self createTabelView];
    [self setupPopHeaderView];
    [self setupData];
    
#ifndef IG_AppStore
    
    [self addTestTag];
#endif
    
    self.isAinamation = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationApp:) name:kRefreshMainVCNotif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateApp) name:@"UpdateApp" object:nil];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setupData {
    
    if (self.city) {
        
        self.popHeaderView.city = self.city;
        
        if ((self.city.lines.count + self.city.views.count) > 0) {
            self.popHeaderView.attractionsGuideImageView.hidden = NO;
        }
        [self reloadMainBG:self.city.pictures];
        [self.tableView reloadData];
        
        [self CityChangeAnimation];
    } else {
        
        NSNumber *lastCityID = [AppManager sharedManager].lastCityID;
        if (lastCityID) {
            
            [self loadDataSourceWithCityID:lastCityID];
            return;
        }
    }
}

- (void)loadDataSourceWithCityID:(NSNumber *)cityID {
    
    if (!cityID) {
        [IGUtils showToast:MYLocalizedString(@"CHANGECITY_UNKONWNCITY", nil)];
        return;
    }
    
    self.isAinamation = YES;
    
    if (!self.city) {
        [ActivityIndicatorView showHUDAddedTo:[UIApplication sharedApplication].keyWindow backgroundColor:kBGColor];
    }
    
    @weakify(self);
    [NetAPIManager getRecommendScenicWithCityID:cityID andBlock:^(City *city, NSError *error) {
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:[UIApplication sharedApplication].keyWindow];
        
        self.city = city;
        self.popHeaderView.city = city;
        
        if ((self.city.lines.count + self.city.views.count) > 0) {
            
            self.popHeaderView.attractionsGuideImageView.hidden = NO;
        } else {
            self.popHeaderView.attractionsGuideImageView.hidden = YES;
        }
        
        [self.tableView reloadData];
        [self initLocation];
        [self reloadMainBG:self.city.pictures];
        [self CityChangeAnimation];
    }];
}

- (void)getLocationCity {
    
    @weakify(self);
    [[LocationManager sharedManager] realLocation:^(CLLocation *location, NSError *error) {
        @strongify(self);
        
        if (!location) {
            return ;
        }
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            CLLocationCoordinate2D coor = transformFromGCJToWGS(location.coordinate, nil);
            
            [NetAPIManager getRecommendScenicWithLocation:coor andBlock:^(City *locationcity, NSError *error) {
                
                self.locationCity = locationcity;
                
                if (!locationcity || locationcity.cid.integerValue == self.city.cid.integerValue) {
                    
                    return ;
                }
                
                if (self.navigationController.visibleViewController != self) {
                    
                    self.needReAlertCity = YES;
                    
                    return;
                }
                
                [self alertLocationCity];
                
            }];
        });
    }];
}

- (void)alertLocationCity {
    
    self.needReAlertCity = NO;
    
    if (!self.locationCity) {
        return;
    }
    
    NSString *msg = [NSString localizedStringWithFormat:MYLocalizedString(@"HOMEPAGE_CHANGE_LOCATION_CITY", nil),self.locationCity.smartName,self.locationCity.smartName];
    
    [IGAlertView alertWithTitle:nil message:msg cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_CONFIRM", nil) commit:^{
        
        self.city = self.locationCity;
        [self initLocation];
        [self setupData];
        [AppManager sharedManager].lastCityID = self.locationCity.cid;
    } cancel:nil];
}

- (void)reloadMainBG:(NSString *)bgURLStr {
    
    if (!bgURLStr) {
        [ActivityIndicatorView hideHUDAddedTo:[UIApplication sharedApplication].keyWindow];
        self.obfuscationImageView.image = [self.imageView.image blurredImageWithRadius:effectValue iterations:5 tintColor:[UIColor blackColor]];
        return;
    }
    
    UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromCacheForKey:bgURLStr];
    
    if (image) {
        BOOL starView = [[NSUserDefaults standardUserDefaults] boolForKey:@"starView"];
        if (!starView) {
            [ActivityIndicatorView hideHUDAddedTo:[UIApplication sharedApplication].keyWindow];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"starView"];
        }
        self.imageView.image = image;
        self.obfuscationImageView.image = [image blurredImageWithRadius:effectValue iterations:5 tintColor:[UIColor blackColor]];
        return;
    }
    
    @weakify(self);
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:bgURLStr] placeholderImage:self.imageView.image completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        @strongify(self);
        
        self.obfuscationImageView.image = [image blurredImageWithRadius:effectValue iterations:5 tintColor:[UIColor blackColor]];
    }];
}

- (void)goSearch {
    
    [MobClick event:@"1_1_1"];
    SearchViewController * searchVC = [[SearchViewController alloc] init];
    searchVC.currentCity = self.city;
    searchVC.gpsCity = self.locationCity;
    searchVC.delegate = self;
    BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:searchVC];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)setUpNavigationItem {
    
    [self leftBarButtonWithImageName:@"menu" selector:@selector(openOrColseLeftList)];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(0, 0, 20, 20);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    self.backBtn.alpha = 0;
    [self.backBtn addTarget:self action:@selector(backTop) forControlEvents:UIControlEventTouchUpInside];
    [self.backBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    
    self.titleView = [[TitleView alloc]init];
    
    
    // ios 11  后 titleView  调整
    if (kiOS11Later) {
        self.titleView.intrinsicContentSize = CGSizeMake(SCREEN_WIDTH - 160, 30);
    }else{
        self.titleView.frame =CGRectMake(0, 0, SCREEN_WIDTH - 160, 30);
    }
    self.titleView.delegate = self;
    self.titleView.title = MYLocalizedString(@"HOMEPAGE_HOTLIST", nil);
    self.navigationItem.titleView = self.titleView;
}

- (void)openOrColseLeftList {
    [MobClick event:@"1_1_8"];
    [self showLeftViewAnimated:nil];
}

- (void)setupBg {
    
    self.barBGAlpha = 0;
    // self.navigationController.navigationBar.translucent = NO;
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.image = [UIImage imageNamed:@"defaultBG"];
    self.obfuscationImageView = [[UIImageView alloc] initWithFrame:self.imageView.bounds];
    self.obfuscationImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    self.obfuscationImageView.image = [[UIImage imageNamed:@"defaultBG"] blurredImageWithRadius:effectValue iterations:5 tintColor:[UIColor blackColor]];
    
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.obfuscationImageView];
    //    [self.view addSubview:self.darkView];
}


- (void)addTestTag {
    
    UILabel *tagLabel = [UILabel new];
    tagLabel.textColor = [UIColor redColor];
    tagLabel.text = [NSString stringWithFormat:@"%@ (version %@, build %@)",[kBaseURLStr componentsSeparatedByString:@"."].firstObject, kVersion,kVersionBuild];
    tagLabel.font = Font(14);
    tagLabel.frame = CGRectMake(0, ISiPhoneX ? 30 : 10, SCREEN_WIDTH, 20);
    tagLabel.textAlignment = NSTextAlignmentCenter;
    [[UIApplication sharedApplication].keyWindow addSubview:tagLabel];
}

//新手引导
- (void)newGuidePage {
    
    if (!self.city) {
        return;
    }
    
    if (self.navigationController.visibleViewController != self) {
        
        self.needReGuide = YES;
        IGLog(@"不是这一页");
        return;
    }
    self.needReGuide = NO;
    
    NSMutableDictionary *tabDict = [NSMutableDictionary dictionaryWithDictionary:@{@"line":@{@"title":@"HOMEPAGE_CITYTOUR",@"imageName":@"urbanline",@"selectedNum":@(CityTourItem)},@"raider":@{@"title":@"HOMEPAGE_STRATEGY",@"imageName":@"推荐行程",@"selectedNum":@(RaidersItem)}}];
    
    
    BOOL hasShowLine = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasShowLine"];
    BOOL hasShowRaider = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasShowRaider"];
    BOOL hasChangeCity = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasChangeCity"];
    
    if (![self.city.tagsArray containsObject:@"line"]|| hasShowLine) {
        [tabDict removeObjectForKey:@"line"];
    }
    if (!self.city.hasstrategy || hasShowRaider) {
        [tabDict removeObjectForKey:@"raider"];
    }
    if (tabDict.count == 0 && hasChangeCity) {
        
        [self getLocationCity];
        
        return;
    }
    
    //添加遮罩指示
    JMHoledView *holedView = [[JMHoledView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view.window addSubview:holedView];
    
    if (hasChangeCity) {
        [self addHoledView:holedView dict:tabDict];
    } else {
        
        TitleView *tView = [[TitleView alloc] init];;
        tView.title = MYLocalizedString(@"HOMEPAGE_HOTLIST", nil);
        
        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
        CGRect rect = [self.titleView convertRect:self.titleView.bounds toView:window];
        
        [holedView addHCustomView:tView onRect:rect];
        
        UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_HOME_CHANGE_CITY", nil)];
        
        UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
        
        CGRect guideRect = CGRectMake(CGRectGetMidX(rect) - guideImage.size.width / 2.0f, CGRectGetMaxY(rect) + 10, guideImage.size.width, guideImage.size.height);
        
        [holedView addHCustomView:imageview onRect:guideRect];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasChangeCity"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    @weakify(self);
    [holedView clickedBlock:^(JMHoledView *holedView, NSInteger index) {
        
        @strongify(self);
        
        if (tabDict.count == 0) {
            [holedView removeFromSuperview];
            [self getLocationCity];
            
        } else {
            [holedView removeHoles];
            NSInteger nextIndex = [self addHoledView:holedView dict:tabDict];
            
            if (nextIndex == 0) {
                [holedView removeFromSuperview];
                [self getLocationCity];
            }
        }
    }];
}

- (NSInteger)addHoledView:(JMHoledView *)holedView dict:(NSMutableDictionary *)tabDict {
    
    UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
    
    for (TabItem *item in self.popHeaderView.mennuView.subviews) {
        
        if (![item isKindOfClass:[TabItem class]]) {
            continue;
        }
        
        if ((item.selectNum == CityTourItem && [tabDict.allKeys containsObject:@"line"])) {
            CGRect rect = [item convertRect:item.bounds toView:window];
            TabItem *myItem = [TabItem initTabItemWith:tabDict[@"line"]];
            myItem.isHot = item.isHot;
            [holedView addHCustomView:myItem onRect:rect];
            
            UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_HOME_CITY_TOUR", nil)];
            
            UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
            
            CGRect guideRect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect) - guideImage.size.height, guideImage.size.width, guideImage.size.height);
            
            [holedView addHCustomView:imageview onRect:guideRect];
            [tabDict removeObjectForKey:@"line"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasShowLine"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return 1;
        }
    }
    
    
    if ([tabDict.allKeys containsObject:@"raider"]) {
        
        CGRect rect = [self.popHeaderView.RaidersBtn convertRect:self.popHeaderView.RaidersBtn.bounds toView:window];
        
        TabItem *myItem = [TabItem initTabItemWith:tabDict[@"raider"]];
        myItem.Ratio = 0.9;
        [holedView addHCustomView:myItem onRect:rect];
        
        
        UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_HOME_STRATEGY", nil)];
        
        UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
        
        CGRect guideRect = CGRectMake(CGRectGetMidX(rect) - guideImage.size.width , CGRectGetMaxY(rect) + 5, guideImage.size.width, guideImage.size.height);
        
        [holedView addHCustomView:imageview onRect:guideRect];
        [tabDict removeObjectForKey:@"raider"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasShowRaider"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return 2;
    }
    return 0;
}

//更新app
- (void)updateApp {
    
    if (!self.hasLoad) {
        return;
    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSString *appVersion = kVersion;
        
        if ([appVersion compare:[AppManager sharedManager].version.version options:NSNumericSearch] == NSOrderedAscending) {
            NSString *msg = [NSString stringWithFormat:@"%@%@%@",appVersion,MYLocalizedString(@"PUBLIC_UPDATETO", nil),[AppManager sharedManager].version.version];
            
            if ([appVersion compare:[AppManager sharedManager].version.minver options:NSNumericSearch] == NSOrderedDescending) {
                
                [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) message:msg cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_UPDATE", nil) commit:^{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/imguider/id1234141200"]];
                    
                } cancel:nil];
                
            } else {
                
                YYCForceUpdateVC *alertVC = [[YYCForceUpdateVC alloc] initWithTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) msg:msg btnTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) handel:^(NSString *ok) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/imguider/id1234141200"]];
                }];
                
                [alertVC showWithVC:self];
            }
        }
    });
}


// 问卷调查
- (void)showQuestion {
    
    if ([[UserManager sharedManager].user.needpaper boolValue] && [UserManager sharedManager].token.length > 0 && [UserManager sharedManager].user.paper.length > 0 && [[UserManager sharedManager].user.role integerValue] != UserRolesTypeLow) {
        
        [UserManager sharedManager].user.needpaper = @(NO).stringValue;
        
        
        BOOL hasShowQuestion = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasShowQuestion"];
        
        if (hasShowQuestion) {
            return;
        }
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasShowQuestion"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self hideLeftView:nil];
            HomeQuestionAlertVC *alerVC = [HomeQuestionAlertVC new];
            
            [alerVC showWithVC:self Block:^{
                
                NSString *url = [NSString stringWithFormat:@"%@%@?platform=ios&lang=%@&country=%@&token=%@",[AppManager sharedManager].baseURLStr,[UserManager sharedManager].user.paper, [AppManager sharedManager].language, [AppManager sharedManager].currentCountryCode,[UserManager sharedManager].token];
                
                //                NSString *testurl = @"https://www.imguider.com/tourist/services/h5wenjuan/4?platform=ios&lang=zh-Hans&country=CN&token=67d755b6f67040c3b06c5c5e15032f5b";
                
                WebViewVC *webVC = [WebViewVC new];
                webVC.url = url;
                [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:webVC] animated:YES completion:nil];
            }];
        });
    }
}

// 外部调起
- (void)operationApp:(NSNotification *)noti {
    
    if ([AppManager sharedManager].opObj == nil) {
        return;
    }
    
    NSInteger type = [AppManager sharedManager].opObj.type;
    NSString *opid = [AppManager sharedManager].opObj.opid;
    [AppManager sharedManager].opObj = nil;
    
    if (type == 1 && opid) {
        
        BaseViewController *currentVC = (BaseViewController *)self.navigationController.visibleViewController;

        if (!currentVC) {
            
            return;
        }
        
        [self popVC:currentVC andEnterOpid:opid];
    }
}

- (void)popVC:(BaseViewController *)vc andEnterOpid:(NSString *)opid {
    
    NSArray *vcArray = self.navigationController.viewControllers;
    
    if (![vcArray containsObject:vc]) {
        
        IGLog(@"---移除 ------");
        
        @weakify(self);
        [vc dismissViewControllerAnimated:NO completion:^{
            @strongify(self);
            BaseViewController *currentVC = (BaseViewController *)self.navigationController.visibleViewController;
            
            [self popVC:currentVC andEnterOpid:opid];
            
        }];
        return;
    }
    
    if ([vc isKindOfClass:[BaseViewController class]]) {
        vc.NoAnimation = YES;
    }
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self hideLeftView:nil];
        LinePreDetailVC *preDetailVC = [IGUtils loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
        preDetailVC.lineid = opid;
        preDetailVC.NoAnimation = YES;
        
        [self.navigationController pushViewController:preDetailVC animated:YES];
    });
}

/**
 app 评分
 */
- (void)appMark {
    
    NSDate *insertDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"insertAppTime"];
    
    if (insertDate) {
        
        NSInteger differentTime = fabs([insertDate timeIntervalSinceNow]);
        
        if (differentTime > (3 * 24 * 60 * 60)) {
            
            NSInteger times = [[NSUserDefaults standardUserDefaults] integerForKey:@"openTimes"];
            
            if (times % 3 == 0) {
                
                [IGAlertView alertWithTitle:MYLocalizedString(@"HOMEPAGE_MARK_APP_TITLE", nil) message:MYLocalizedString(@"HOMEPAGE_MARK_APP_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"HOMEPAGE_MARK_APP_CANCEL", nil) commitBtn:MYLocalizedString(@"HOMEPAGE_MARK_APP_CONFORM", nil) commit:^{
                    
                    NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id1234141200?action=write-review"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"insertAppTime"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                } cancel:^{
                    
                    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"insertAppTime"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }];
            }
        }
    }
}

- (UIView *)tableViewHeaderView {
    
    if (!_tableViewHeaderView) {
        _tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,SCREEN_HEIGHT - 64 - kNavigationBarHeight)];
        _tableViewHeaderView.backgroundColor = [UIColor clearColor];
    }
    return _tableViewHeaderView;
}

- (void)setupPopHeaderView {
    
    self.popHeaderView = [[PopHeaderView alloc] initWithFrame:self.tableViewHeaderView.bounds];
    self.popHeaderView.delegate = self;
    [self.tableViewHeaderView addSubview:self.popHeaderView];
}
- (void)createTabelView {
    
    CGFloat space = kNavigationBarHeight;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space, SCREEN_WIDTH, SCREEN_HEIGHT - space) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = self.tableViewHeaderView;
    [self.view addSubview:self.tableView];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"ScenicIntroductioncell" bundle:nil] forCellReuseIdentifier:@"ScenicIntroductioncell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CityTourIntroduceCell" bundle:nil] forCellReuseIdentifier:@"CityTourIntroduceCell"];
    
}

- (void)backTop {
    [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    [MobClick event:@"1_0_3"];
}

#pragma mark -PopHeaderViewDelegate

- (void)selecteItemWith:(SelectedNum)selectedNum {
    switch (selectedNum) {
        case ScenicItem:
        {
            [self Scenic_SpotBtnClicked];
        }
            break;
        case CityTourItem:
        {
            [self cityTourClicked];
        }
            break;
        case GuiderItem:
        {
            [self guiderBtnClicked];
        }
            break;
        case RaidersItem:
        {
            [self raidersBtnClicked];
        }
            break;
            
        default:
            break;
    }
}

- (void)raidersBtnClicked {
    
    RaidersViewController * vc = [[RaidersViewController alloc] init];
    vc.currentCityID = self.city.cid;
    vc.Bgimage = self.obfuscationImageView.image;;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)cityTourClicked {
    [MobClick event:@"1_1_3"];
    
    CityTourCardVC * vc = [[CityTourCardVC alloc] init];
    vc.Bgimage = self.obfuscationImageView.image;
    vc.cityID = self.city.cid;
    vc.title = MYLocalizedString(@"CITYTOURLIST_TITLE", nil);
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)mapBtnClicked {
    [MobClick event:@"1_1_2"];
    MapVC *mapVC = [[MapVC alloc] init];
    mapVC.city = self.city;
    [self.navigationController pushViewController:mapVC animated:YES];
}
- (void)Scenic_SpotBtnClicked {
    [MobClick event:@"1_1_4"];
    ScenicSpotViewController * scenicSpotVC = [ScenicSpotViewController new];
    scenicSpotVC.Bgimage = self.obfuscationImageView.image;
    scenicSpotVC.city = self.city;
    scenicSpotVC.title = MYLocalizedString(@"SITELIST_TITLE", nil);
    [self.navigationController pushViewController:scenicSpotVC animated:YES];
}
- (void)guiderBtnClicked {
    [MobClick event:@"1_1_5"];
    GuiderVC * guiderVC = [[GuiderVC alloc] init];
    guiderVC.Bgimage = self.obfuscationImageView.image;
    guiderVC.currentCityID = self.city.cid;
    guiderVC.title = MYLocalizedString(@"GUIDELIST_TITLE", nil);
    [self.navigationController pushViewController:guiderVC animated:YES];
}

#pragma mark - tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return  self.city.lines.count + self.city.views.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerView"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] init];
        footerView.backgroundColor = [UIColor clearColor];
    }
    
    return footerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        
        CGFloat height = SCREEN_HEIGHT - cellHight - kNavigationBarHeight;
        
        if (height < 0) {
            return 0.1;
        }
        return height;
    }
    
    return 0.00000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.0000001;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < self.city.lines.count) {
        
        LineModel * model = self.city.lines[indexPath.row];
        CityTourIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityTourIntroduceCell"];
        
        [cell  configDataWintLineModel:model];
        
        return cell;
    }else {
        
        
        ScenicIntroductioncell *  cell = [tableView dequeueReusableCellWithIdentifier:@"ScenicIntroductioncell"];
        Scenic * scenic = self.city.views[indexPath.row - self.city.lines.count];
        
        [cell configScenicWith:scenic];
        
        IGLog(@"^^^^^^^^^^%@",scenic.pictures);
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  cellHight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    AskQuestionVC *vc = [AskQuestionVC new];
    //    [self.navigationController pushViewController:vc animated:YES];
    //    return;
    
    
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    CGFloat centerY = tableView.contentOffset.y + tableView.frame.size.height * 0.5;
    // IGLog(@"%f----%f",cell.center.y,centerY);
    if (fabs(cell.center.y - centerY) > 150) {
        
        return;
    }
    
    self.currentIndexPath = indexPath;
    
    if (indexPath.row < self.city.lines.count) {
        
        
        LineModel *model = self.city.lines[indexPath.row];
        
        LinePreDetailVC *preDetailVC = [IGUtils loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
        
        preDetailVC.lineid = model.lineid;
        
        self.navigationController.delegate = preDetailVC;
        
        [self.navigationController pushViewController:preDetailVC animated:YES];
        
        [MobClick event:@"1_1_6"];
        
    } else {
        
        Scenic *scenic = self.city.views[indexPath.row - self.city.lines.count];
        
        ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
        
        self.navigationController.delegate = scenicDesVC;
        
        scenicDesVC.scenic = scenic;
        [self.navigationController pushViewController:scenicDesVC animated:YES];
        
        [MobClick event:@"1_1_7"];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)initLocation {
    
    self.obfuscationImageView.alpha = 0;
    self.view.userInteractionEnabled = NO;
    [self.tableView setContentOffset:CGPointMake(0, -134) animated:NO];
}
- (void)CityChangeAnimation {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        self.view.userInteractionEnabled = YES;
        self.isAinamation = NO;
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self newGuidePage];
    });
    
}

//- (void)CreateTimer{
//    [_timer invalidate];
//    _timer = nil;
//    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(Restore) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
//    [_timer setFireDate:[NSDate distantPast]];
//}
//
//- (void)Restore {
//    CGFloat yOffset = self.tableView.contentOffset.y;
//    yOffset += 28.8;
//    IGLog(@"%f",yOffset);
//
//    if (yOffset >= -30) {
//        self.tableView.contentOffset = CGPointMake(0, 0);
//        [self.timer invalidate];
//    }
//    self.tableView.contentOffset = CGPointMake(0, yOffset);
//}
#pragma mark scrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = self.tableView.contentOffset.y;
    CGFloat height = self.tableViewHeaderView.frame.size.height;
    
    CGFloat factor = -yOffset +height;
    CGRect f = CGRectMake(0, yOffset, SCREEN_WIDTH, factor);
    [self.popHeaderView updateLocation:f];
    
    if (yOffset <= (SCREEN_HEIGHT - 64 - kNavigationBarHeight)) {
        self.popHeaderView.alpha = 1 - yOffset/SCREEN_HEIGHT*3;
        
        
        self.titleView.searchView.alpha = 1 - yOffset/(SCREEN_HEIGHT - 64 - kNavigationBarHeight);
        _backBtn.alpha = yOffset/(SCREEN_HEIGHT - 64 - kNavigationBarHeight);
        
        self.titleView.titleLabel.alpha = yOffset/(SCREEN_HEIGHT - 64 - kNavigationBarHeight);
        
        if (self.titleView.searchView.alpha < 0.5) {
            self.titleView.searchView.userInteractionEnabled = NO;
        }else {
            self.titleView.searchView.userInteractionEnabled = YES;
        }
    }
    
    if (yOffset < 0) {
        
        CGFloat alpha = 1 + yOffset / 80.0f;
        
        if (alpha > 1) {
            alpha = 1;
        } else if (alpha < 0 ) {
            alpha = 0;
        }
        
        self.obfuscationImageView.alpha = alpha;
        
    } else {
        self.obfuscationImageView.alpha = 1;
    }
    
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    _currentOffset = scrollView.contentOffset.y;
}


- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    
    if ((self.city.lines.count + self.city.views.count) == 0) {
        return;
    }
    
    if (scrollView.contentOffset.y < cellHight ) {
        if (scrollView.contentOffset.y >= _currentOffset ) {
            NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:0];
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        } else {
            [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }
    } else if ((scrollView.contentOffset.y - _currentOffset)>2 ) {
        
        
        int num = (scrollView.contentOffset.y - cellHight)/ cellHight +1;
        NSIndexPath *index = nil;
        if (num < (self.city.lines.count + self.city.views.count)) {
            index = [NSIndexPath indexPathForRow:num inSection:0];
            
        } else {
            
            index = [NSIndexPath indexPathForRow:(self.city.lines.count + self.city.views.count) - 1 inSection:0];
        }
        IGLog(@"****%d",num);
        [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        
    } else {
        int num = (scrollView.contentOffset.y - cellHight)/ (cellHight)+1;
        if (num > 0) {
            NSIndexPath * index = [NSIndexPath indexPathForRow:num - 1  inSection:0];
            IGLog(@"****%d",num);
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        } else {
            [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }
    }
    
    IGLog(@"WWWWWWWWWWWW%f",scrollView.contentOffset.y);
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    
    if ((self.city.lines.count + self.city.views.count) == 0) {
        return;
    }
    
    if (scrollView.contentOffset.y < cellHight ) {
        if (scrollView.contentOffset.y - _currentOffset > cellHight/2 ) {
            NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:0];
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        } else {
            [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }
    } else if (fabs(scrollView.contentOffset.y - _currentOffset)>cellHight/2  ) {
        
        
        int num = (scrollView.contentOffset.y - cellHight)/ cellHight +1;;
        NSIndexPath *index = nil;
        if (num < (self.city.lines.count + self.city.views.count)) {
            index = [NSIndexPath indexPathForRow:num inSection:0];
            
        } else {
            
            index = [NSIndexPath indexPathForRow:(self.city.lines.count + self.city.views.count) - 1 inSection:0];
        }
        IGLog(@"****%d",num);
        [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        
    } else {
        int num = (scrollView.contentOffset.y - cellHight)/ cellHight +1;
        
        if (num > 0) {
            
            NSIndexPath * index = [NSIndexPath indexPathForRow:num - 1  inSection:0];
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        } else {
            [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }
        
    }
}

- (void)selectScenicID:(NSString *)ScenicID {
    
    Scenic *scenic = [Scenic new];
    scenic.ID = ScenicID;
    
    ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
    
    scenicDesVC.scenic = scenic;
    [self.navigationController pushViewController:scenicDesVC animated:YES];
}

//- (void)selectCityID:(NSString *)cityID {
//
//}

- (void)loginActionTapped {
    
    LoginVC *loginVC = [LoginVC new];
    loginVC.delegate = self;
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
}


- (void)loginSuccessCallback {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
}

#pragma mark -SearchViewControllerDelegate
- (void)selectCity:(City *)city {
    
    if (city.cid == self.city.cid) {
        return;
    }
    self.city = city;
    // self.popHeaderView.city = city;
    [self loadDataSourceWithCityID:city.cid];
}

- (void)selectCityID:(NSString *)cityID {
    
    [self loadDataSourceWithCityID:@(cityID.integerValue)];
}

@end

